//
//  TogetherDateArrangerViewController.m
//  Together_iOS
//
//  Created by applex on 14-2-28.
//  Copyright (c) 2014年 QIU Shuang. All rights reserved.
//

#import "TogetherDateArrangerViewController.h"
#import "TogetherDateArrangerCell.h"
#import "Plan.h"
#import "TogetherStopSettingView.h"
#import "TogetherToolbar.h"
#import "RMSwipeTableViewCell.h"
#import "TogetherHttpClient.h"
#import "TogetherBaiduMapViewController.h"
#import "AFNetworking.h"
#import "TogetherStoreListViewController.h"

@interface TogetherDateArrangerViewController () <RMSwipeTableViewCellDelegate>

@property (nonatomic, strong) TogetherStopSettingView *stopSettingView;
@property (strong, nonatomic) NSMutableDictionary *eventsByStartTime;
@property (strong, nonatomic) NSMutableArray *selectedEvents;

@end

@implementation TogetherDateArrangerViewController

@synthesize tableView = _tableView;
@synthesize addItem = _addItem;

@synthesize eventsByStartTime = _eventsByStartTime;
@synthesize selectedEvents = _selectedEvents;


- (TogetherStopSettingView *) stopSettingView {
    if (!_stopSettingView) {
        _stopSettingView = [[TogetherStopSettingView alloc] initWithFrame:CGRectZero];
        _stopSettingView.viewController = self;
        [self.view addSubview:_stopSettingView];
        _stopSettingView.delegate = self;
    }
    
    return _stopSettingView;
}


- (id)init
{
    self = [super init];
    if (self) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		self.tableView.dataSource = self;
		self.tableView.delegate = self;
        
        self.addItem = [[UIButton alloc] initWithFrame:CGRectZero];
        [self.view setBackgroundColor:[[UIColor alloc] initWithRed:0.965 green:0.957 blue:0.918 alpha:1]];
    }
    return self;
}


- (void)loadView {
    [super loadView];
    self.tableView.frame = CGRectMake(4, 4, 302, 350);
    [self.tableView setBackgroundColor:[[UIColor alloc] initWithRed:0.965 green:0.957 blue:0.918 alpha:1]];
    [self.view addSubview:self.tableView];
    
    self.addItem.frame = CGRectMake(127, 397, 63, 63);
    [self.addItem setImage:[UIImage imageNamed:@"btn_add@2x.png"]forState:UIControlStateNormal];
    [self.addItem addTarget:self action:@selector(showSettingView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addItem];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(125, 467, 100, 15)];
    label.text = @"添加项目";
    [label setTextColor:[[UIColor alloc] initWithRed:0.925 green:0.4 blue:0.051 alpha:1.0]];
    [self.view addSubview:label];
    
    TogetherToolbar *toolbar = [[TogetherToolbar alloc] initWithFrame:CGRectMake(0, 524, 320, 44)];
    toolbar.delegate = self;
    [self.view addSubview:toolbar];
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationItem.rightBarButtonItem.title = @"完成";
    self.tableView.separatorColor = [UIColor clearColor];
    
    /*
     //test code
     NSManagedObjectContext *context = [Stop mainQueueContext];
     
     NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
     fetchRequest.entity = [Stop entityWithContext:context];
     fetchRequest.predicate = [NSPredicate predicateWithFormat:@"remoteID = 0"];
     fetchRequest.fetchLimit = 1;
     
     //Execute the fetch request
     NSArray *results = [context executeFetchRequest:fetchRequest error:nil];
     
     self.selectedEvents = [results mutableCopy];
     */
        
    [self.tableView reloadData];
}


- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    
    if ([self.selectedEvents count]) {
        /*
        Plan *newPlan = [[Plan alloc] init];
        newPlan.stops = self.selectedEvents;
        newPlan.createdTime = [NSDate date];
        newPlan.planDate = [self.selectedEvents firstObject];
         */
    
        TogetherBaiduMapViewController *mapViewController = [[TogetherBaiduMapViewController alloc] init];
        mapViewController.stops = self.selectedEvents;
        UINavigationController *subnavigation = [[UINavigationController alloc] initWithRootViewController:mapViewController];
        UIColor *navBgColor = [[UIColor alloc] initWithRed:255./255. green:114./255. blue:19./255. alpha:1.0];
        [subnavigation.navigationBar setBarTintColor:navBgColor];
        [self.navigationController presentViewController:subnavigation animated:NO completion:nil];
    }
    self.navigationItem.rightBarButtonItem.title = @"完成";
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDelegate


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.selectedEvents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"dateArrangerCellIdentifier";
    TogetherDateArrangerCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[TogetherDateArrangerCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.delegate = self;
        cell.viewController = self;
    }
    
    cell.event = [self.selectedEvents objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Stop *stop = [self.selectedEvents objectAtIndex:indexPath.row];
    TogetherStoreListViewController *storeListViewController = [[TogetherStoreListViewController alloc] init];
    storeListViewController.businessName = stop.name;
    storeListViewController.indexPath = indexPath;
    storeListViewController.viewController = self;
    [self.navigationController pushViewController:storeListViewController animated:YES];
}


#pragma mark - Actions

- (void)didBussinessIdSelected:(NSString *)businessId forIndexPath:(NSIndexPath *)indexPath {
    NSString *url = [[TogetherHttpClient serverAddress] stringByAppendingFormat:@"/business/%@", businessId];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        NSDictionary *dic = (NSDictionary *)responseObject;
        if ([dic[@"status"] isEqualToString:@"OK"]) {
            NSDictionary *stopDic = dic[@"business"];
            Stop *stop = [Stop objectWithDictionary:stopDic];
            [stop save];
            [self.selectedEvents setObject:stop atIndexedSubscript:indexPath.row];
            [self.tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
}


- (void)showSettingView:(id)sender {
    self.stopSettingView.stop = nil;
    [self.stopSettingView showSettingView:nil];
}


#pragma mark - TogetherToolbar actions
- (void) myTrack {
    
}

- (void) hotTracks {
    
}

#pragma mark - TogetherRecommendationProtocol action
- (void) recommendationReceived:(NSMutableArray *)events onDate:(NSDate *)date {
    if ([events count]) {
        if (!self.selectedEvents) {
            self.selectedEvents = [NSMutableArray arrayWithCapacity:10];
            // set event
        }
        
        for (Stop *event in events) {
            event.startTime = date;
        }
        
        [self.selectedEvents addObject:[events objectAtIndex:0]];

        if (!self.eventsByStartTime) {
            self.eventsByStartTime = [NSMutableDictionary dictionary];
        }
        [self.eventsByStartTime setObject:events forKey:((Stop *)[events objectAtIndex:0]).startTime];

        NSArray *sortedEvents = [self.selectedEvents sortedArrayUsingComparator:^NSComparisonResult(id o1, id o2){
            NSDate *first = ((Stop *)o1).startTime;
            NSDate *second = ((Stop *)o2).startTime;
            
            return [first compare:second];
        }];
        self.selectedEvents = [NSMutableArray arrayWithArray:sortedEvents];
        
        [self.tableView reloadData];
    }
}


- (NSArray *)beforeStops:(NSInteger)index {
    if (index <= 0) {
        return nil;
    } else {
        return [self.selectedEvents objectsAtIndexes:[[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, index)]];
    }
}


- (NSArray *)afterStops:(NSInteger)index {
    if (index >= self.selectedEvents.count - 1) {
        return nil;
    } else {
        return [self.selectedEvents objectsAtIndexes:[[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(index + 1, self.selectedEvents.count - index - 1)]];
    }
}


- (NSArray *)excludedStops:(NSInteger)index {
    Stop *selectedStop = [self.selectedEvents objectAtIndex:index];
    Stop *recs = [self.eventsByStartTime objectForKey:selectedStop.startTime];
    NSMutableArray *arr = [recs mutableCopy];
    [arr removeObject:selectedStop];
    return arr;
}


#pragma mark - RMSwipeTableViewCellDelegate

-(void)swipeTableViewCellWillResetState:(RMSwipeTableViewCell *)swipeTableViewCell fromPoint:(CGPoint)point animation:(RMSwipeTableViewCellAnimationType)animation velocity:(CGPoint)velocity {
    if (point.x >= CGRectGetHeight(swipeTableViewCell.frame) - 20.) {
        
        NSIndexPath *indexPath = [self.tableView indexPathForCell:swipeTableViewCell];
        
        NSInteger index = indexPath.row;
        Stop *currentEvent = [self.selectedEvents objectAtIndex:index];
        __block NSArray *recommendations = [self.eventsByStartTime objectForKey:currentEvent.startTime];

        
        void (^loadNext)(int currentIndex) = ^(int currentIndex) {
            Stop *nextEvent = [recommendations objectAtIndex:currentIndex + 1];
            TogetherDateArrangerCell *arrangerCell = (TogetherDateArrangerCell *)swipeTableViewCell;
            [arrangerCell setEvent:nextEvent];
            [self.selectedEvents setObject:nextEvent atIndexedSubscript:index];
        };
        
        // TODO: if last is reached, but network has not finished, should deal with this.
        
        if (!recommendations) {
            recommendations = @[];
            [TogetherHttpClient fetchPredictedStopsWithRegion:currentEvent.regions
                                                         type:[currentEvent.type intValue]
                                                       before:[self beforeStops:index]
                                                        after:[self afterStops:index]
                                                  excludesIds:[self excludedStops:index]
                                                       userId:@(1)
                                                      success:^(NSArray *stops) {
                                                          recommendations = [recommendations arrayByAddingObjectsFromArray:stops];
                                                          if (!self.eventsByStartTime) {
                                                              self.eventsByStartTime = [NSMutableDictionary dictionary];
                                                          }
                                                          [self.eventsByStartTime setObject:recommendations forKey:currentEvent.startTime];
                                                          loadNext(-1);
                                                      }
                                                      failure:^(NSError *error) {
                                                          
                                                      }];
        } else {
            NSInteger currentIndex = [recommendations indexOfObject:currentEvent];
            if (currentIndex == NSNotFound) {
                currentIndex = 0;
            }
            if (currentIndex >= recommendations.count - 3) {
                [TogetherHttpClient fetchPredictedStopsWithRegion:currentEvent.regions
                                                             type:[currentEvent.type intValue]
                                                           before:[self beforeStops:index]
                                                            after:[self afterStops:index]
                                                      excludesIds:[self excludedStops:index]
                                                           userId:@(1)
                                                          success:^(NSArray *stops) {
                                                              recommendations = [recommendations arrayByAddingObjectsFromArray:stops];
                                                              [self.eventsByStartTime setObject:recommendations forKey:currentEvent.startTime];
                                                          }
                                                          failure:^(NSError *error) {
                                                              
                                                          }];
            }
            loadNext(currentIndex);
        }
        
        
        
    } else if (point.x < 0 && -point.x >= CGRectGetHeight(swipeTableViewCell.frame) - 20.) {
        swipeTableViewCell.shouldAnimateCellReset = NO;
        [[(TogetherDateArrangerCell *)swipeTableViewCell checkmarkGreyImageView] removeFromSuperview];
        [UIView animateWithDuration:0.25
                              delay:0
                            options:UIViewAnimationCurveLinear
                         animations:^{
                             swipeTableViewCell.contentView.frame = CGRectOffset(swipeTableViewCell.contentView.bounds, swipeTableViewCell.contentView.frame.size.width, 0);
                         }
                         completion:^(BOOL finished) {
                             [swipeTableViewCell.contentView setHidden:YES];
                             NSIndexPath *indexPath = [self.tableView indexPathForCell:swipeTableViewCell];
                             Stop *event = [self.selectedEvents objectAtIndex:indexPath.row];
                             [self.selectedEvents removeObjectAtIndex:indexPath.row];
                             [self.eventsByStartTime removeObjectForKey:event.startTime];
                             [self.tableView beginUpdates];
                             [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                             [self.tableView endUpdates];
                         }
         ];
    }
}

-(void)swipeTableViewCellDidResetState:(RMSwipeTableViewCell *)swipeTableViewCell fromPoint:(CGPoint)point animation:(RMSwipeTableViewCellAnimationType)animation velocity:(CGPoint)velocity {
    if (point.x < 0 && -point.x > CGRectGetHeight(swipeTableViewCell.frame) - 20.) {
        [swipeTableViewCell.contentView setHidden:YES];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:swipeTableViewCell];
        Stop *event = [self.selectedEvents objectAtIndex:indexPath.row];
        [self.eventsByStartTime removeObjectForKey:event.startTime];
        [self.selectedEvents removeObjectAtIndex:indexPath.row];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}

- (void) done {
    
}


@end
